import { defineStore } from 'pinia'
import { addUser, getUser, getUsers, removeUser, updateUser } from '@/service/modules/system'
import type { PaginationForm, UserModel } from '@/types'

interface systemStoreState {
  userList: UserModel[]
  userTotal: number
}

const useSystemStore = defineStore('system', {
  state: (): systemStoreState => ({
    userList: [],
    userTotal: 0,
  }),
  actions: {
    // 列表
    async getUsersAction(queryParams: PaginationForm) {
      const { data: result } = await getUsers(queryParams)
      this.userList = result.rows
      this.userTotal = result.total
    },
    // 详情
    getUserAction(id: number) {
      return new Promise(async (resolve, reject) => {
        try {
          const { data: result } = await getUser(id)
          resolve(result)
        } catch (err) {
          reject(err)
        }
      })
    },
    // 删除
    async removeUserAction(id: number) {
      try {
        await removeUser(id)
        this.getUsersAction({ page_index: 1, page_size: 10 })
      } catch (error) {}
    },
    // 添加
    async addUserAction(userForm: any) {
      await addUser(userForm)
      this.getUsersAction({ page_index: 1, page_size: 10 })
    },
    // 编辑
    async updateUserAction(id: number, userForm: any) {
      await updateUser(id, userForm)
      this.getUsersAction({ page_index: 1, page_size: 10 })
    },
  },
})
export default useSystemStore
